# coding:utf-8
from __future__ import division
import argparse
import datetime
import os
import subprocess
import sys
import re
import pysequoiadb
from pysequoiadb import client
from pysequoiadb.error import SDBBaseError
from pysequoiadb.error import InvalidParameter


flags = argparse.ArgumentParser()
flags.add_argument("--ip", type=str, required=True, help="addr of ip")
flags.add_argument("--nc", type=str, required=True, help="name of network card")

args = flags.parse_args()

sdb_ip = "10.244.171.142"
sdb_port = "11810"
sdb_user = "peter"
sdb_password = "Foxconn99."
collection_name = "network"
trafficvalues = [0, 0]
exe_time = 60


def read_network_card(nc=args.nc, dir="/data/script"):
    os.chdir(dir)
    # REW:grep技巧
    res = subprocess.Popen("sh net.sh " + nc + " | grep " + nc, shell=True, stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
    in_out = res.stdout.read()
    error_p = re.compile("syntax")
    if re.search(error_p, in_out):
        print("网卡有误，请重新输入")
        sys.exit(0)
    patter = re.compile("\s+")
    in_out = re.split(patter, in_out)  # 网卡名 in out
    return in_out[:3]


def read_in_out_traffic(in_out):
    global trafficvalues
    in_, out_ = in_out[1:3]

    def cal_traffic(traffic, i):
        pat = re.compile('B')
        candiate = re.split(pat, traffic, maxsplit=1)[0]
        tail = candiate[-1]
        try:
            tail = int(tail)
        except:

            if candiate[-1] == "K":
                if float(candiate[:-1]) > 1024.0:
                    trafficvalues[i] += (float(candiate[:-1]) / 1024.0)
                else:
                    trafficvalues[i] += 0
            elif candiate[-1] == "M":
                if float(candiate[:-1]) > 1.0:
                    trafficvalues[i] += float(candiate[:-1])
            else:
                # todo: GB TB PB
                trafficvalues[i] += (float(candiate[:-1]) * 1024.0)
        else:
            # 小于1M 忽略
            trafficvalues[i] += 0

    cal_traffic(in_, 0)
    cal_traffic(out_, 1)


def cal_traffic_mean():
    global trafficvalues
    in_traffic, out_traffic = trafficvalues
    in_mean_traffic = float("%.2f" % (in_traffic / exe_time))
    out_mean_traffic = float("%.2f" % (out_traffic / exe_time))
    trafficvalues[0] = 0.0
    trafficvalues[1] = 0.0
    return in_mean_traffic, out_mean_traffic


def main():
    try:
        db = client(sdb_ip, sdb_port, sdb_user, sdb_password)
    except SDBBaseError, e:
        pysequoiadb._print(e)
        print "连接出错 请校验"
        sys.exit(0)
    cs = db.get_collection_space('face')
    # 没有就创
    try:
        cl = cs.get_collection(collection_name)
    except SDBBaseError, e:
        cl = cs.create_collection(collection_name, {'ShardingKey': {"_id": 1},
                                                    'ShardingType': "hash",
                                                    'Partition': 65536,
                                                    'ReplSize': 1,
                                                    'Compressed': True,
                                                    'AutoSplit': True})

    while 1:  # 死循环
        for i in range(exe_time):
            nc_info = read_network_card()
            read_in_out_traffic(nc_info)

        in_mean_traffic, out_mean_traffic = cal_traffic_mean()
        # cl.insert()
        timezone = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        info_dict = {
            "ip": args.ip,
            'net_in': in_mean_traffic,
            'net_out': out_mean_traffic,
            'time': timezone
        }
        try:
            cl.insert(info_dict)
        except InvalidParameter as e:
            print e.detail
            print "插入出错，请重启"


if __name__ == "__main__":
    main()